<script setup lang="ts">
import {getAssignTreeApi} from "@/api/user";
import {saveRoleMenuApi} from "@/api/role";
import {reactive, ref} from "vue";
import SysDialog from "@/components/SysDialog.vue";
import useDialog from "@/hooks/useDialog";
import {userStore} from "@/store/user";
import {ElMessage, ElTree} from "element-plus";
const {dialog,onShow,onClose} = useDialog()
const store = userStore()
const treeRef = ref<InstanceType<typeof ElTree>>()
//权限树数据
const assignTreeData = reactive({
  list:[],
  checked:[]
})
//数据查询的参数
const parms = reactive({
  userId:'',
  roleId:''
})
const defaultProps={
  children: 'children',
  label: 'title'
}
const checked = (id:number,data:any,newArr:any)=>{
  data.forEach((item:any)=>{
    if(item.menuId==id){
      if(item.children && item.children.length==0){newArr.push(item.menuId)}
    }else{
      if(item.children && item.children.length!=0){
        //递归调用获取
        checked(id,item.children,newArr)
      }

    }
  })
}
//查询菜单树
const getAssignTree= async ()=>{
    let res = await getAssignTreeApi(parms)
    if(res && res.code==200){
        assignTreeData.list = res.data.menuList
        assignTreeData.checked = res.data.checkList
      //数据回显。判断角色是否已经分配过菜单，如果有，显示
      if(assignTreeData.checked.length>0){
        let newArr:any=[]
        assignTreeData.checked.forEach((item)=>{
          checked(item,assignTreeData.list,newArr)
        })
        assignTreeData.checked = newArr
      }
    }

}
//提交分配的权限表单
const commitParm = reactive({
  roleId:'',
  menuIdList:[] as string[]
})
//弹框显示
const show = async (roleId:string,name:string)=>{
  commitParm.roleId = roleId
  assignTreeData.checked = []
  assignTreeData.list = []
  commitParm.menuIdList = []
  parms.roleId = roleId
  parms.userId = store.getUserId
  dialog.height = 450
  dialog.width = 300
  dialog.title = '为【'+name+']分配菜单'
  await getAssignTree()
  onShow()
}

const commit=async()=>{
    const checkIds = treeRef.value?.getCheckedKeys() as string[]
    const halfCheckIds = treeRef.value?.getHalfCheckedKeys() as string[]
    let ids = checkIds?.concat(halfCheckIds)
    //设置选中的节点id
    commitParm.menuIdList=ids
    if(ids.length==0){
      ElMessage.error('请选择菜单')
      return
    }
    //获取选中的菜单数据
    let res = await saveRoleMenuApi(commitParm)
    if(res && res.code==200){
        ElMessage.success(res.message)
        onClose()
    }
}
//暴漏出去给外部组件使用
defineExpose({
  show
})
</script>

<template>
  <SysDialog :title="dialog.title" :width="dialog.width" :height="dialog.height" :visible="dialog.visible"
  @on-close="onClose" @on-confirm="commit">
    <template v-slot:content>
      <el-tree ref="treeRef" node-key="menuId" show-checkbox default-expand-all :default-checked-keys="assignTreeData.checked" :data="assignTreeData.list" :props="defaultProps"></el-tree>
    </template>
  </SysDialog>
</template>

<style scoped lang="scss">

</style>